import { ref, onMounted, onUnmounted } from 'vue';
import { Img, Img1, ADMIN_S } from '@/components/cesium/map.config';

export const useToggleMap = () => {
  const isPopupVisible = ref(false);
  const selectedType = ref<string | null>('imageMap');
  const togglePopup = () => {
    isPopupVisible.value = !isPopupVisible.value;
  };

  const closePopup = () => {
    isPopupVisible.value = false;
  };

  // 防止点击地图也关闭对话框
  const selectItem = (type: string) => {
    if (selectedType.value === type) return;
    selectedType.value = selectedType.value === type ? null : type;
    window.viewer.imageryLayers.removeAll();
    if (selectedType.value === 'imageMap') {
      // 天地图影像
      window.viewer.imageryLayers.addImageryProvider(Img);
      // 天地图影像注记
      window.viewer.imageryLayers.addImageryProvider(Img1);
    } else {
      //行政地图
      window.viewer.imageryLayers.addImageryProvider(ADMIN_S);
    }
  };
  // 点击外部关闭
  const handleClickOutside = (event: MouseEvent) => {
    const popupBox = document.querySelector('.popup-box');
    const iconButton = document.querySelector('.icon-button');

    if (popupBox && iconButton && !popupBox.contains(event.target as Node) && !iconButton.contains(event.target as Node)) {
      closePopup();
    }
  };

  // 添加全局点击事件监听
  onMounted(() => {
    document.addEventListener('click', handleClickOutside);
  });

  // 组件卸载时移除监听
  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
  });
  return {
    isPopupVisible,
    selectedType,
    togglePopup,
    closePopup,
    selectItem
  };
};
